<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <!-- 搜索表单 -->
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="3" style="padding-bottom: 2px">
              <v-text-field
                label="部门名称"
                v-model="queryParams.deptName"
                placeholder="请输入部门名称"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 250px;"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px;max-width: 150px;margin-left: -1rem">
              <v-select
                label="状态"
                v-model="queryParams.status"
                :items="statusOptions"
                item-text="dictLabel"
                item-value="dictValue"
                dense
                outlined
                clearable
                style="width: 130px;"
              ></v-select>
            </v-col>

            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>

    <v-row style="margin-bottom: -5px;margin-top: 0;">
      <v-col md="1" style="max-width: 84px">
        <v-btn
          color="primary"
          plain
          small
          outlined
          @click="handleAdd"
          v-hasPermi="['system:dept:add']">
          <v-icon left>
            mdi-plus
          </v-icon>
          新增
        </v-btn>
      </v-col>
      <v-col style="float: right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </v-col>
    </v-row>

    <v-main>
      <v-data-table
        :headers="headers"
        :items="deptList"
        hide-default-footer
        :loading="loading"
        loading-text="加载中,请稍后.."
        item-key="deptId"
        no-data-text="暂无数据"
        style="margin-left: 16px"
      >
        <template v-slot:body>
        </template>
      </v-data-table>
      <v-treeview
                  ref="deptTree"
                  dense
                  hoverable
                  open-all
                  :items="deptList" style="font-size: 14px;padding: 0!important;margin: 0 !important;"
      >
        <!-- 插槽 -->
        <template v-slot:prepend="{ item, open }" style="padding: 0 !important;margin: 0 !important;">
          <span style="display: inline-block;width: 264px;padding: 0 16px">
            {{ item.deptName }}
          </span>
            <span style="display: inline-block;width: 159px;padding: 0 16px;text-align: center">
            {{ item.orderNum }}
          </span>
            <span style="display: inline-block;width: 212px;padding: 0 16px;text-align: center;">
            {{ statusFormat(item) }}
          </span>
            <span style="display: inline-block;width: 200px;padding: 0 16px;text-align: center">
            {{ item.createTime }}
          </span>
            <!-- 操作 -->
            <span style="display: inline-block;text-align: center;padding: 0 16px;">
            <v-btn text
                   small
                   plain
                   height="20"
                   width="40"
                   @click="handleUpdate(item)"
                   v-hasPermi="['system:dept:edit']">
              <v-icon small>
                mdi-pencil
              </v-icon>
              修改
            </v-btn>
            <v-btn
              color="primary"
              plain
              small
              height="20"
              width="40"
              @click="handleAdd(item)"
              v-hasPermi="['system:dept:add']">
              <v-icon small>
                mdi-plus
              </v-icon>
              新增
            </v-btn>
            <span v-if="item && !item.showConfirmDelete">
              <v-btn color="#C62828"
                     small
                     plain
                     height="20"
                     width="40"
                     @click="onClickDelete(item)">
                <v-icon small>
                  mdi-delete
                </v-icon>
                删除
              </v-btn>
            </span>
              <!-- 删除确认 -->
            <span v-else>
              <v-tooltip top>
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    small color="error"
                    plain
                    height="20"
                    width="40"
                    v-bind="attrs"
                    v-on="on"
                    @click="handleDelete(item)"
                    v-hasPermi="['system:dept:remove']">
                    <v-icon small>
                      mdi-delete
                    </v-icon>
                    确定
                  </v-btn>
                </template>
                <span>请再次点击确定删除</span>
              </v-tooltip>
            </span>
          </span>
        </template>
      </v-treeview>
    </v-main>

    <!-- 编辑对话框 -->
    <v-dialog
      v-model="visible"
      persistent
      max-width="600px">

      <v-card>
        <!-- 对话框标题 -->
        <v-card-title>
          <span style="font-size: 18px">{{ title }}</span>
        </v-card-title>

        <!-- 表单 -->
        <v-form ref="form" v-model="valid">
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12" sm="12">
                  <v-menu
                    ref="menu"
                    v-model="showDeptOption"
                    transition="scale-transition"
                    offset-y
                    max-width="550px"
                    style="padding: 0"
                  >
                    <template v-slot:activator="{ on, attrs }">
                      <v-text-field
                        v-model="form.parentName"
                        :rules="rules.parentId"
                        label="*上级部门"
                        placeholder="选择上级部门"
                        v-bind="attrs"
                        v-on="on"
                        dense
                        style="padding: 0"
                      ></v-text-field>
                    </template>
                    <v-treeview
                      ref="tree"
                      dense
                      activatable
                      hoverable
                      return-object
                      :items="deptOptions" style="font-size: 14px;padding: 0;background-color: white;min-width: 500px !important;max-height: 450px;overflow: auto;"
                    >
                      <!-- 插槽 -->
                      <template v-slot:prepend="{ item, open }">
                        <div @click="handleNodeClick(item)">
                          {{ item.deptName }}
                        </div>
                      </template>
                    </v-treeview>
                  </v-menu>
                </v-col>

                <v-col cols="12" sm="6">
                  <v-text-field
                    v-model="form.deptName"
                    label="*部门名称"
                    placeholder="请输入部门名称"
                    :rules="rules.deptName"
                    clearable
                    dense
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="8" md="6">
                  <v-text-field
                    v-model="form.orderNum"
                    label="*显示排序"
                    :rules="[rules.orderNum]"
                    type="number"
                    clearable
                    :min="0"
                    dense
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="6" >
                  <v-text-field
                    v-model="form.leader"
                    :rules="rules.leader"
                    label="负责人"
                    placeholder="请输入负责人"
                    required
                    clearable
                    dense
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="6">
                  <v-text-field
                    v-model="form.phone"
                    :rules="[rules.phone]"
                    label="联系电话"
                    placeholder="请输入联系电话"
                    required
                    clearable
                    dense
                  ></v-text-field>
                </v-col>

                <v-col cols="12" sm="6">
                  <v-text-field
                    v-model="form.email"
                    :rules="[rules.email]"
                    label="邮箱"
                    placeholder="请输入邮箱"
                    required
                    clearable
                    dense
                    hint="xxx@example.com"
                  ></v-text-field>
                </v-col>
                <v-col cols="12" sm="6">
                  <v-radio-group
                    label="部门状态"
                    v-model="form.status"
                    row dense style="margin: 0;"
                  >
                    <v-radio
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    ></v-radio>
                  </v-radio-group>
                </v-col>
              </v-row>
            </v-container>
            <small class="ml10">*表示必需字段</small>
          </v-card-text>
        </v-form>

        <!-- 底部操作按钮 -->
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            text
            @click="updateVisible(false)">
            取消
          </v-btn>
          <v-btn
            color="blue darken-1"
            text
            @click="submitForm">
            保存
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Dept",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      visible: false,
      // 表单参数
      form: {},
      valid: false,
      // 是否显示部门选择
      showDeptOption: false,
      headers: [
        { text: '部门名称', value: 'deptName', align: 'left', sortable: false, width: '240' },
        { text: '排序', value: 'orderNum', sortable: false, align: 'center', width: '150px' },
        { text: '状态', value: 'status', sortable: false, align: 'center', width: '200px'},
        { text: '创建时间', value: 'createTime', align: 'center', sortable: false, width: '200px' },
        { text: '操作', value: 'actions',  sortable: false, width: '300px'  },
      ],
      // 表单校验
      rules: {
        parentId: [
          val => (val || '').length > 0 || '上级部门不能为空'
        ],
        deptName: [
          val => (val || '').length > 0 || '部门名称不能为空'
        ],
        orderNum: [
          val => (val || '').length > 0 || '菜单顺序不能为空'
        ],
        email: value => {
          if (value) {
            const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            return pattern.test(value) || '请输入正确的邮箱地址'
          }
        },
        phone: value => {
          if (value) {
            const pattern = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
            return pattern.test(value) || '请输入正确的手机号码'
          }
        }
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, "deptId");
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 部门节点单击事件
    handleNodeClick(data) {
      if (data) {
        this.form.parentId = data.deptId;
        this.form.parentName = data.deptName;
      }
    },
    // 字典状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "1"
      };
      if (this.$refs.form) {
        this.$refs.form.resetValidation();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
        this.form.parentName = row.deptName;
      }
      this.title = "添加部门";
      this.visible = true;
      listDept().then(response => {
	        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.title = "修改部门";
        this.visible = true;
      });
      listDeptExcludeChild(row.deptId).then(response => {
	        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    validate () {
      this.$refs.form.validate()
    },
    /** 提交按钮 */
    async submitForm() {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      await this.validate();
      if (this.valid) {
        if (this.form.deptId != undefined) {
          await updateDept(this.form).then(res => {
            this.$store.dispatch('snackbar/openSnackbar',{
              msg: '修改成功',
              color: 'success'
            })
            this.getList();
            this.visible = false;

          });
        } else {
          await addDept(this.form).then(res => {
            this.$store.dispatch('snackbar/openSnackbar',{
              msg: '新增成功',
              color: 'success'
            })
            this.getList();
            this.visible = false;
          });
        }
      }
    },
    // 调用父级关闭对话框, 并重置表单
    updateVisible(value) {
      this.reset();
      this.visible = value;
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete(item) {
      this.$set(item, 'showConfirmDelete', true);
      setTimeout(() => {
        this.$set(item, 'showConfirmDelete', false);
      }, 3500);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      await delDept(row.deptId).then(res => {
        if (res) {
          // 使用全局消息提示
          this.$store.dispatch('snackbar/openSnackbar', {
            msg: '删除成功',
            color: 'success'
          })
          this.getList();
        }
      });
    },

  }
};
</script>

<style>
  .v-list-group__header {
    padding: 0 16px 0 0 !important;
  }

  .v-treeview-node__root {
    padding: 0 !important;
  }
</style>
